package com.example.pingxue.service;

import com.example.pingxue.entity.Course;
import com.example.pingxue.entity.Student;
import com.example.pingxue.entity.TClass;
import com.example.pingxue.entity.Teacher;
import com.example.pingxue.repository.*;
import jakarta.persistence.EntityNotFoundException;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class ClassService {
    private final ClassRepository classRepository;
    private final TeacherRepository teacherRepository;
    private final CourseRepository courseRepository;

    // 行为3：查看班级花名册
    public Set<Student> getRoster(Long classId) {
        TClass clazz = classRepository.findById(classId)
                .orElseThrow(() -> new EntityNotFoundException("班级不存在"));

        // 转换为学生集合并处理序列化
        return clazz.getSelections().stream()
                .map(selection -> {
                    Student student = selection.getStudent();
                    // 解除循环引用
                    student.getSelections().clear();
                    return student;
                })
                .collect(Collectors.toSet());
    }

    // 行为4：给教学班分配上课教师
    @Transactional
    public void assignTeacher(Long classId, Long teacherId) {
        TClass clazz = classRepository.getById(classId);
        Teacher teacher = teacherRepository.getById(teacherId);

        // 移除旧关联
        if (clazz.getTeacher() != null) {
            clazz.getTeacher().getClazz().remove(clazz);
        }

        // 建立新关联
        clazz.setTeacher(teacher);
        teacher.getClazz().add(clazz);

        classRepository.save(clazz);
    }

    // 行为5：给教学班设置对应的课程
    @Transactional
    public void setCourse(Long classId, Long courseId) {
        TClass clazz = classRepository.getById(classId);
        Course course = courseRepository.getById(courseId);

        // 移除旧关联
        if (clazz.getCourse() != null) {
            clazz.getCourse().getClses().remove(clazz);
        }

        // 建立新关联
        clazz.setCourse(course);
        course.getClses().add(clazz);

        classRepository.save(clazz);
    }
}
